<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="4" style="min-width: 250px">
        <div class="add">
          <el-button @click="handleAddLevel1" style="width: 100%"
            >添加一级分类</el-button
          >
        </div>
        <el-tree
          :data="deptOptions"
          :props="{ label: 'dictName', children: 'children' }"
          :expand-on-click-node="false"
          ref="deptTreeRef"
          node-key="id"
          highlight-current
          :default-expand-all="false"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="edit">
                <el-tooltip content="添加分类" placement="top">
                  <a @click.stop="append(data)">
                    <el-icon><Plus /></el-icon>
                  </a>
                </el-tooltip>
                <el-tooltip content="编辑" placement="top">
                  <a style="margin-left: 8px" @click.stop="handelEdit(data)">
                    <el-icon><Edit /></el-icon>
                  </a>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <a
                    style="margin-left: 8px"
                    @click.stop="handelDelClass(data)"
                  >
                    <el-icon><DeleteFilled /></el-icon>
                  </a>
                </el-tooltip>
              </span>
            </span>
          </template> </el-tree
      ></el-col>
      <el-col :span="20">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="标准名称" prop="bookName">
            <el-input
              v-model="queryParams.bookName"
              placeholder="请输入标准名称"
            />
          </el-form-item>
          <!-- <el-form-item label="条件筛选" prop="conditionalFiltering">
            <el-select
              v-model="queryParams.conditionalFiltering"
              placeholder="请选择"
            >
              <el-option
                v-for="item in conditionList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="标准分类" prop="standardId">
            <el-select v-model="queryParams.standardId" placeholder="请选择">
              <el-option
                v-for="item in standardList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="语言类型" prop="language">
            <el-select v-model="queryParams.language" placeholder="请选择">
              <el-option
                v-for="item in languageList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态" prop="language">
            <el-select v-model="queryParams.commitFlag" placeholder="请选择">
              <el-option label="草稿" value="0"></el-option>
              <el-option label="审核中" value="1"></el-option>
              <el-option label="审批通过" value="2"></el-option>
              <el-option label="审批驳回" value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="small" @click="handleQuery"
              >搜索</el-button
            >
            <el-button size="small" @click="resetQuery">重置</el-button>
            <!-- <el-button type="primary" plain size="small" @click="handleAdd"
              >新增</el-button
            > -->
          </el-form-item>
        </el-form>

        <el-row>
          <el-col :span="24">
            <el-table v-loading="loading" :data="libraryList">
              <el-table-column label="序号" align="center" prop="id" />
              <el-table-column
                label="标准名称"
                align="center"
                prop="bookName"
              />
              <el-table-column
                label="简介"
                align="center"
                prop="description"
                show-overflow-tooltip
              />
              <!-- <el-table-column
                label="条件筛选"
                align="center"
                prop="standardCategoryIds"
              >
                <template #default="scope">
                  {{ mapDict(conditionList, scope.row.standardCategoryIds) }}
                </template>
              </el-table-column> -->
              <el-table-column
                label="标准分类"
                align="center"
                prop="standardId"
              >
                <template #default="scope">
                  {{ mapDict(standardList, scope.row.standardId) }}
                </template>
              </el-table-column>
              <el-table-column label="语言类型" align="center" prop="language">
                <template #default="scope">
                  {{ mapDict(languageList, scope.row.language) }}
                </template>
              </el-table-column>
              <el-table-column
                label="审核状态"
                align="center"
                prop="formateType"
              >
                <template #default="scope">
                  <div v-if="scope.row.commitFlag == 0">
                    <span class="el-tag el-tag--primary">草稿</span>
                  </div>
                  <div v-if="scope.row.commitFlag == 1">
                    <span class="el-tag el-tag--warning">审核中</span>
                  </div>
                  <div v-if="scope.row.commitFlag == 2">
                    <span class="el-tag el-tag--success">审批通过</span>
                  </div>
                  <div v-if="scope.row.commitFlag == 3">
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="scope.row.approvalPass"
                      :disabled="!scope.row.approvalPass"
                      placement="top"
                    >
                      <span class="el-tag el-tag--danger">审批驳回</span>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column
                label="检索树标签"
                align="center"
                prop="retrieveTags"
              /> -->

              <el-table-column
                label="标准状态"
                align="center"
                prop="status"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ mapDict2(statusList, scope.row.status) }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="状态" align="center" prop="status" /> -->
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="250"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    >查看详情</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="el-icon-edit"
                    @click="handelStatusChange(scope.row, 2)"
                    :disabled="
                      scope.row.commitFlag == 2 || scope.row.commitFlag == 3
                    "
                    >通过</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="el-icon-edit"
                    @click="handelStatusChange(scope.row, 3)"
                    :disabled="
                      scope.row.commitFlag == 2 || scope.row.commitFlag == 3
                    "
                    >驳回</el-button
                  >
                  <!-- <el-button
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    link
                    type="primary"
                    >删除</el-button
                  > -->
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 30]"
          layout="->,total,sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="currentChange"
      /></el-col>
    </el-row>

    <!-- 添加分类log框 -->
    <el-dialog
      :title="`${classForm.id ? '编辑' : '新增'}分类`"
      v-model="classdialogVisible"
      width="30%"
      @close="beforeClose1"
    >
      <el-form
        :model="classForm"
        ref="ruleFormRef"
        label-width="120px"
        :rules="rules1"
      >
        <el-form-item label="分类" prop="dictName">
          <el-input v-model.trim="classForm.dictName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="编码" prop="dictValue">
          <el-input
            :disabled="isEdit"
            v-model.trim="classForm.dictValue"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="排序" prop="dictSequence">
          <el-input
            v-model.number="classForm.dictSequence"
            style="width: 300px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="classdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handelNewClass"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加或修改标准库信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="60%"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        disabled
      >
        <el-form-item label="标准名称" prop="bookName">
          <el-input v-model.trim="form.bookName" placeholder="请输入标准名称" />
        </el-form-item>
        <el-form-item label="标准简介" prop="description">
          <el-input
            v-model.trim="form.description"
            type="textarea"
            placeholder="请输入标准简介"
          />
        </el-form-item>
        <el-form-item label="适用范围" prop="scopeDescription">
          <el-input
            v-model.trim="form.scopeDescription"
            type="textarea"
            placeholder="请输入标准简介"
          />
        </el-form-item>
        <el-form-item label="标准状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="item in statusList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标准号" prop="standardCode">
          <el-input
            v-model.trim="form.standardCode"
            placeholder="请输入标准号"
          />
        </el-form-item>
        <!-- 标准类别 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="标准类别" prop="retrieveTags">
              <el-cascader
                style="width: 500px"
                v-model="form.retrieveTags"
                :options="deptOptions"
                :props="{
                  checkStrictly: true,
                  label: 'dictName',
                  value: 'id',
                  children: 'children',
                  emitPath: false,
                }"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="30" prop="standardId">
              <el-select v-model="form.standardId" placeholder="请选择">
                <el-option
                  v-for="item in standardList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="0" prop="standardCategoryIds">
              <el-select
                v-model="form.standardCategoryIds"
                placeholder="请选择"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="item in conditionList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 实施时间 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="实施时间" prop="effectDate">
              <el-date-picker
                v-model="form.effectDate"
                type="datetime"
                placeholder="请选择实施时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发布时间" prop="releaseDate">
              <el-date-picker
                v-model="form.releaseDate"
                type="datetime"
                placeholder="请选择发布时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="发布机构" prop="releaseInstitution">
          <el-input
            v-model.trim="form.releaseInstitution"
            placeholder="请输入发布机构"
          />
        </el-form-item>
        <el-form-item label="语言类型" prop="language">
          <el-select v-model="form.language" placeholder="请选择">
            <el-option
              v-for="item in languageList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-select
            style="width: 100%"
            v-model="form.keyword"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
          >
            <!-- <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="起草单位">
          <el-input v-model.trim="form.draftCompony" />
        </el-form-item>
        <el-form-item label="起草人">
          <el-input v-model.trim="form.draftBy" />
        </el-form-item>
        <el-form-item label="缩略图" prop="coverFiles">
          <UploadImg
            :uploadId="0"
            @file-uploaded="handleFileUploaded"
            @file-remove="handleRemoveImg"
            :imglist="appFileImages"
            tip="仅允许上传图片文件！"
          />
        </el-form-item>
        <el-form-item label="封面" prop="pdfHomePageFiles">
          <UploadImg
            :uploadId="1"
            @file-uploaded="handleFileUploaded"
            @file-remove="handleRemoveImg"
            :imglist="appFilePdfHomeImages"
            tip="仅允许上传图片文件！"
          />
        </el-form-item>
        <el-form-item label="目录" prop="pdfCatalogFiles">
          <UploadImg
            :uploadId="2"
            @file-uploaded="handleFileUploaded"
            @file-remove="handleRemoveImg"
            :imglist="appFilePdfCatalogImages"
            tip="仅允许上传图片文件！"
          />
        </el-form-item>
        <el-form-item label="附件" prop="contentFiles">
          <uploadFile
            :uploadId="0"
            :limit="1"
            @file-uploaded="handleFileUpload"
            @file-remove="handleRemoveFile"
            :Filelist="appFiles"
            tip="仅允许 .pdf,.doc,.docx 格式 最大10M"
            accept=".pdf,.doc,.docx"
            :maxSize="10"
            :fileType="[
              'application/pdf',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
              'application/msword',
            ]"
          />
        </el-form-item>
        <el-form-item label="展示范围" prop="dataScope">
          <el-cascader
            v-model="form.dataScope"
            :options="scopeList"
            :props="{
              multiple: false,
              emitPath: false,
              label: 'label',
              value: 'value',
              children: 'children',
            }"
            collapse-tags
            clearable
          />
        </el-form-item>
        <el-form-item label="上传人">
          <el-input v-model="form.uploadBy" style="width: 260px" />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-input v-model="form.uploadTime" style="width: 260px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm('0')"
            >保存草稿</el-button
          >
          <el-button type="primary" @click="submitForm('1')"
            >提交审批</el-button
          > -->
          <el-button @click="cancel">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import UploadImg from "@/components/CustomUpload";
import uploadFile from "@/components/UploadFile/UploadFile.vue";
import {
  listLibrary,
  getLibrary,
  delLibrary,
  addLibrary,
} from "@/api/system/library";
import {
  getTypeListRequest,
  getDeteilImgByIdRequest,
} from "@/api/public/index.js";
import {
  getDickAllTreeListRequest,
  insertModelType,
  updateModelType,
  deleteModelType,
} from "@/api/buildlibrary";
import { changeApprovalRequest } from "@/api/library/examineLibrary";
import { rules } from "./rules.js";
import { ElMessage, ElMessageBox } from "element-plus";
import pagination from "@/components/pagination";

export default {
  name: "Library",
  components: {
    UploadImg,
    uploadFile,
    pagination,
  },
  data() {
    return {
      //分类规则
      rules: rules,

      rules1: {
        dictName: [
          { required: true, message: "请输入分类", trigger: "change" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "change",
          },
        ],
        dictValue: [
          { required: true, message: "请输入编码", trigger: "change" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 50 个字符",
            trigger: "change",
          },
        ],
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标准库信息表格数据
      libraryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        //检索树标签
        retrieveTags: null,
        bookName: null,
        description: null,
        standardCategoryIds: null,
        standardId: null,
        language: null,
        formateType: null,
        retrieveTags: null,
        downloadNum: null,
        coverFileId: null,
        status: null,
        commitFlag: null,
      },

      // 表单参数
      form: {
        bookName: "", //标准名称
        description: "", //描述
        scopeDescription: "", //适用范围
        status: "", //标准状态
        standardCode: "", //标准号
        retrieveTags: "", //标准类别
        standardId: "", //标准筛选
        standardCategoryIds: [], //条件筛选
        effectDate: "", //实施时间
        releaseDate: "", //发布时间
        releaseInstitution: "", //发布机构
        language: "", //语言类型
        keyword: [], //关键词
        draftCompony: "", //起草单位
        draftBy: "", //起草人
        coverFiles: [], //缩略图文件
        pdfHomePageFiles: [], //PDF首页图片
        pdfCatalogFiles: [], //pdf目录图片
        contentFiles: [], //附件
        dataScope: "", //展示范围
        uploadBy: "", //上传人
        uploadTime: "", //上传时间

        formateType: "",
        commitFlag: 0, //状态
      },
      // 表单校验

      //条件赛选字典
      conditionList: [],
      //标准筛选字典
      standardList: [],
      //语言筛选字典
      languageList: [],
      //标准状态字典
      statusList: [],

      //展示范围字典
      scopeList: [],

      //树结构
      deptOptions: [],
      //存的所有id
      Allids: [],
      //是否添加编辑弹窗
      classdialogVisible: false,
      parentDictValue: null,
      //添加分类的表单
      classForm: {
        dictName: "", //分类名称
        dictValue: "", //编码
        dictType: "", //dictType
        parentId: 0, //父ID
        dictStatus: 0, //状态
        dictSequence: 0, //排序
      },
      //缩略图图片文件列表
      appFileImages: [],
      //PDF首页图片文件列表
      appFilePdfHomeImages: [],
      //PDF目录图片文件列表
      appFilePdfCatalogImages: [],
      //文件列表
      appFiles: [],
      //当前选择的左侧树id
      currentTreeId: 0,
      //是否编辑状态
      isEdit: false,
    };
  },
  created() {
    this.getList();

    this.getTypeList();

    this.getTreeList();
  },
  methods: {
    //分页器操作
    currentChange(value) {
      this.queryParams.current = value;
      this.getList();
    },
    //分页器size事件
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getList();
    },
    //映射操作
    mapDict(dict, id) {
      return dict.find((item) => item.id == id)?.label;
    },
    //映射操作
    mapDict2(dict, id) {
      return dict.find((item) => item.id == id)?.label;
    },
    //获取字典数据
    async getTypeList() {
      //使用promiseall 请求三个字典
      const res = await Promise.all([
        getTypeListRequest({ size: 999, model: { type: 7 } }), //条件筛选
        getTypeListRequest({ size: 999, model: { type: 6 } }), //标准分类
        getTypeListRequest({ size: 999, model: { type: 8 } }), //语言类型
        getTypeListRequest({ size: 999, model: { type: 10 } }), //标准状态
        getTypeListRequest({ size: 999, model: { type: 13 } }), //展示范围
        getTypeListRequest({ size: 999, model: { type: 16 } }), //展示范围
      ]);
      this.conditionList = res[0].data.records;
      this.standardList = res[1].data.records;
      this.languageList = res[2].data.records;
      this.statusList = res[3].data.records;
      this.scopeList = [...res[4].data.records, ...res[5].data.records];
    },
    //获取树结构数据
    async getTreeList() {
      const res = await getDickAllTreeListRequest({ level: 5, dictType: 4 });
      this.deptOptions = res.data;
      console.log(res);
    },
    //添加分类方法
    //新建分类方法
    append(row) {
      this.classdialogVisible = true;
      console.log(row);
      this.classForm.dictValue = row.dictValue + (row.children.length + 1);
      this.classForm.dictSequence = row.children.length + 1;
      this.parentDictValue = row.dictValue;
      this.classForm.dictType = row.dictType;
      this.classForm.parentId = row.id;
    },

    /** 查询标准库信息列表 */
    getList() {
      this.loading = true;
      listLibrary(this.queryParams).then((response) => {
        this.libraryList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    handleNodeClick(nodeData) {
      // 递归查找所有父节点
      const parentNodes = this.findParentNodes(nodeData);
      parentNodes.unshift(nodeData.id);
      let ids = parentNodes.reverse();
      console.log(ids);
      this.currentTreeId = nodeData.id;
      this.Allids = ids;
      //请求数据
      this.queryParams.retrieveTags = nodeData.id;
      this.getList();
    },

    //新建顶级分类
    handleAddLevel1() {
      this.classdialogVisible = true;
      this.classForm.dictType = "4";
      this.classForm.parentId = 0;
      this.parentDictValue = null;
    },

    //新建分类提交表单确认方法
    handelNewClass() {
      this.$refs.ruleFormRef.validate(async (valid, fields) => {
        if (valid) {
          let data = {
            ...this.classForm,
          };

          data.dictValue =
            (this.parentDictValue ? this.parentDictValue : "") + data.dictValue;
          console.log(data);
          // return;
          let fun = data.id ? updateModelType : insertModelType;
          const { code } = await fun(data);
          if (code === 200) {
            ElMessage.success(`${data.id ? "编辑" : "添加"}成功`);
            this.classdialogVisible = false;
            this.parentDictValue = null;
            this.getTreeList();
          } else {
            ElMessage.error("服务故障，稍后再试");
            this.parentDictValue = null;
          }
        } else {
          console.log("error submit!", fields);
        }
      });
    },
    //编辑左侧菜单
    handelEdit(row) {
      console.log(row);
      this.isEdit = true; //编辑模式
      this.classdialogVisible = true;
      this.classForm.dictName = row.dictName; //分类名称
      this.classForm.dictValue = row.dictValue; //编码
      this.classForm.parentId = row.parentId; //父级名称
      this.classForm.dictType = row.dictType; //类型
      this.classForm.dictStatus = 0; //状态
      this.classForm.id = row.id; //id
      this.classForm.dictSequence = row.dictSequence; //排序
    },
    selectNodeClick(nodeData) {
      console.log(111);
    },

    //关闭dlog回调
    beforeClose1() {
      this.isEdit = false; //退出编辑模式
      console.log(1123123);
      //数据初始化
      this.classForm = {
        dictName: "",
        dictValue: "",
        dictType: "",
        parentId: 0,
        dictStatus: 0,
        dictSequence: 0,
      };
    },
    //图片上传事件
    handleFileUploaded(data) {
      console.log(data);
      switch (data.uploadId) {
        case 0:
          this.form.coverFiles = data.fileData;
          break;
        case 1:
          this.form.pdfHomePageFiles = data.fileData;
          break;
        case 2:
          this.form.pdfCatalogFiles = data.fileData;
          break;
      }
    },
    //图片移除事件
    handleRemoveImg(data) {
      console.log(data);
      if (!data.fileData.id) {
        return;
      }
      switch (data.uploadId) {
        case 0:
          this.form.coverIds.push(data.fileData.id);
          if (data.fileList.length === 0) {
            this.form.coverFiles = [];
          }

          break;
        case 1:
          this.form.pdfHomePageIds.push(data.fileData.id);
          if (data.fileList.length === 0) {
            this.form.pdfHomePageFiles = [];
          }

          break;
        case 2:
          this.form.pdfCatalogIds.push(data.fileData.id);
          if (data.fileList.length === 0) {
            this.form.pdfCatalogFiles = [];
          }

          break;
      }
    },
    //文件移除事件
    handleRemoveFile(data) {
      console.log(data);
      if (!data.fileData.id) {
        return;
      }
      switch (data.uploadId) {
        case 0:
          this.form.contentIds.push(data.fileData.id);
          if (data.fileList.length === 0) {
            this.form.contentFiles = [];
          }
          break;
      }
    },
    //文件上传事件
    handleFileUpload(data) {
      console.log(data);
      switch (data.uploadId) {
        case 0:
          this.form.contentFiles = data.fileData;
          this.form.formateType = data.fileData[0].name.split(".").pop();
          break;
      }
    },

    findParentNodes(nodeData) {
      const parentNodes = [];
      let treeref = this.$refs["deptTreeRef"];
      // console.log(nodeData);

      const findParent = (node) => {
        let pid = treeref.getNode(node).parent.data.id || 0;
        // console.log(pid);
        // console.log(treeref.getNode(node).parent.data);
        if (pid !== 0) {
          parentNodes.push(pid);
          findParent(treeref.getNode(node).parent.data);
        }
      };
      findParent(nodeData);
      return parentNodes;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = { current: 1, model: {}, size: 10 };
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标准库信息";
      this.appFileImages = [];
      this.appFiles = [];
    },
    //关闭对话框之后的回调
    closeDialog() {
      this.appFileImages = [];
      this.appFiles = [];
      this.appFilePdfHomeImages = [];
      this.appFilePdfCatalogImages = [];
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      this.form.id = row.id;
      this.form.bookName = row.bookName;
      this.form.description = row.description;
      this.form.scopeDescription = row.scopeDescription;
      this.form.status = parseInt(row.status);
      this.form.standardCode = row.standardCode;
      this.form.retrieveTags = row.retrieveTags;
      this.form.standardId = row.standardId;
      this.form.standardCategoryIds = row.standardCategoryIds.map((item) =>
        parseInt(item)
      );
      this.form.effectDate = row.effectDate;
      this.form.releaseDate = row.releaseDate;
      this.form.releaseInstitution = row.releaseInstitution;
      this.form.language = row.language;
      this.form.keyword = row.keyword ? row.keyword.split(",") : [];
      this.form.draftCompony = row.draftCompony;
      this.form.draftBy = row.draftBy;
      this.form.formateType = row.formateType;

      this.form.coverIds = []; //删除的封面图片ID集合
      this.form.pdfHomePageIds = []; //删除的PDF首页ID集合
      this.form.pdfCatalogIds = []; //删除的PDF目录ID集合

      this.form.contentIds = []; //删除的文档ID集合

      this.open = true;
      this.title = "查看标准库信息";

      this.form.coverFiles = 1;
      this.form.contentFiles = 1;
      this.form.pdfHomePageFiles = 1;
      this.form.pdfCatalogFiles = 1;

      this.appFileImages = this.mapImgUrl(row.coverFiles);
      this.appFilePdfHomeImages = this.mapImgUrl(row.pdfHomePageFiles);
      this.appFilePdfCatalogImages = this.mapImgUrl(row.pdfCatalogFiles);
      // this.appFileImages = await this.getimgurlbyid(row.coverFiles);

      this.appFiles = this.getFileName(row.contentFiles);

      this.form.dataScope = row.dataScope.toString(); //展示范围
      this.form.uploadBy = row.createBy; //上传人
      this.form.uploadTime = row.createTime; //上传时间
      // getLibrary(id).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改标准库信息";
      // });
    },
    mapImgUrl(list) {
      if (!list) return [];
      return list.map((item) => {
        return {
          name: item.fileName,
          id: item.id,
          url: item.filePath,
        };
      });
    },

    //获取文件名
    getFileName(data) {
      let temp = [];
      data.forEach((item) => {
        if (item.fileName) {
          temp.push({
            name: item.fileName,
            id: item.id,
          });
        }
      });
      return temp;
    },

    //审批通过和驳回  2通过 3 驳回
    handelStatusChange(row, state) {
      // changeApprovalRequest

      if (state === 2) {
        ElMessageBox.confirm("确定要审核通过吗?", "提示", {
          confirmButtonText: "确认通过",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              const { code } = await changeApprovalRequest({
                id: row.id,
                commitFlag: state,
              });
              if (code === 200) {
                ElMessage.success(`操作成功`);
                this.getList();
              } else {
                ElMessage.error(`服务器故障，稍后再试`);
              }
            } catch (error) {}
          })
          .catch(() => {});
      }

      if (state === 3) {
        ElMessageBox.prompt("拒绝原因", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,

          inputErrorMessage: "拒绝原因不能为空",
        })
          .then(async ({ value }) => {
            const { code } = await changeApprovalRequest({
              id: row.id,
              commitFlag: state,
              approvalPass: value,
            });
            if (code === 200) {
              ElMessage.success(`操作成功`);
              this.getList();
            } else {
              ElMessage.error(`服务器故障，稍后再试`);
            }
          })
          .catch(() => {});
      }
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-row) {
  flex-wrap: nowrap;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .edit {
    display: none;
  }
  &:hover {
    // display: block;
    // background-color: red;
    .edit {
      display: block;
    }
  }
}
// .avatar-uploader-icon {
//   width: 100px;
//   height: 100px;
// }
// :deep(.el-upload-list__item) {
//   width: 400px;
// }
</style>
